import axios from 'axios'
import { Message, Loading } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
const baseUrl = 'http://119.3.69.218/admin'
// const baseUrl = 'http://3255e17c09.wicp.vip:8888/admin/'
// const baseUrl = 'http://192.168.0.229:8099/'
// const baseUrl = 'http://119.23.28.225:8088/admin/'
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  baseURL: baseUrl,
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
  // withCredentials: true // send cookies when cross-domain requests
}) 
function error(msg, type = 'error', time = 2000) {
  Message({
    message: msg,
    type: type,
    duration: time
  })
}
let loading
let responseAll = false
function startLoading(config) { // 使用Element loading-start 方法
  try {
    if (!config.headers.noloading) {
      loading = Loading.service({
        lock: true,
        text: '请等待...',
        background: 'rgba(255,255,255,0)'
      })
      setTimeout(() => {
        if (loading) {
          loading.close()
        }
      }, 3000)
    }
  } catch (e) {
  }
}
function endLoading() { // 使用Element loading-close 方法
  if (loading) {
    loading.close()
  }
}
// Request interceptors
service.interceptors.request.use(
  (config) => {
    responseAll = false
    startLoading(config)
    // Add X-Access-Token header to every request, you can add other custom headers here
    if (store.getters.token) {
      config.headers['Authorization'] = getToken()
    }
    if (config.headers.allResponse) {
      responseAll = true
    }
    return config
  },
  (error) => {
    responseAll = false
    Promise.reject(error)
  }
)

// Response interceptors
service.interceptors.response.use(
  (response) => {
    endLoading()
    const res = response.data
    if (responseAll) {
      return response
    }
    if (res.code == 200) {
      return res
    } else {
      error(res.message || '系统繁忙')
      return Promise.reject()
    }
  },
  (error) => {
    endLoading()
    error(error.message)
    return Promise.reject(error)
  }
)

export default service
